const express = require('express')   //引用
const app = express()

app.use(express.json())

app.use(require('cors')())  //允许跨域


//连接数据库
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/element-admin',{
    useNewUrlParser:true,

})


//数据库模型
const Article =mongoose.model('Article',new mongoose.Schema({
    title:{type:String},
    body:{type:String},
}))


app.get('/',async (req,res)=>{
    res.send('index')
})


//新增文章
app.post('/api/articles', async (req,res)=>{
    const article = await Article.create(req.body)
    res.send('article')
})

//显示文章列表
app.get('/api/bodylists', async (req,res)=>{
    const bodylist = await Article.find()
    res.send(bodylist)
})

// app.get('/api/bodylists', async function(req,res){
//     const bodylist = await Article.find()
//     res.send(bodylist)
// })

//删除文章
app.delete('/api/articles/:id', async (req,res)=>{
    await Article.findByIdAndDelete(req.params.id)
    res.send({
        status:true
    })
})

//文章详情
app.get('/api/articles/:id', async (req,res)=>{
    const article = await Article.findById(req.params.id)
    res.send(article)
})

//修改文章详情内容
app.put('/api/articles/:id', async (req,res)=>{
    const article = await Article.findByIdAndUpdate(req.params.id, req.body)
    res.send(article)
})

app.listen(4001,()=>{
    console.log('http://localhost:4001');
    
})